import { useEffect, useRef, useState } from 'react'
import './ShoppingCar.less'
import { useContextData } from '/src/components/Context'
import decreaseImg from '/src/assets/decrease.png'
import addImg from '/src/assets/add.png'
import carImg from '/src/assets/car.png'


export default function () {
  const boxDom = useRef<HTMLElement>()
  const [show, setShow] = useState(false)
  const [totalPrice,setTotalPrice] = useState(0)

  const {contextData, setContextData} = useContextData() as any
  const {goodsList,langKey} = contextData

  useEffect(() =>{
   const total = (goodsList as any[])
    .reduce((prev, cur) => {
      return +(prev.toFixed(2)) + cur.price * cur.count
    },0)
    setTotalPrice(total)
  },[goodsList])

  function countChange(number:number, name:string){
    console.log(number, name)
    setContextData( (data:any) => {
      const list = JSON.parse(JSON.stringify(data.goodsList)) as any[]
      const index = list.map(val => val.name)
      .indexOf(name)
      if(index !== -1){
        list[index].count += number
        if( list[index].count <= 0){
          list.splice(index,1)
        }
      }
      return {
        ...data,
        goodsList: list
      }
    })

  }


  //根据点击坐标判断是否关闭购物车列表
  useEffect(() => {
   
    // document.body.onclick = (e:any) => {
    //   const el = ( boxDom.current as HTMLElement)
    //   const pos = el.getBoundingClientRect()
    //   if( !( e.pageX > pos.left  && e.pageY > pos.top)){
    //     setShow(false)
    //   }
    // }
  },[])
  

  return (
    <div comp="shoppingcar" >
      <div ref={boxDom}  className={['main', show ? 'show' : ''].join(' ')}>
      <div className={'desc-box'}>
        <span>我的点菜</span>
        <span onClick={() =>  setContextData({...contextData, goodsList:[]})}>清空</span>
      </div>
      <ul  className={'select-list-box'}>
        {
          (goodsList as any[]).map((item, i) => {
            return <li key={i}>
            <div className="left">
              {item[langKey]}
            </div>
            <div className="right">
              <span className="amount">￥{item.price}</span>
              <div className="number-box">
                <img src={decreaseImg} onClick={() => countChange(-1, item.name)} alt="" />
                <span>{item.count||0}</span>
                <img className='add' onClick={() => countChange(1, item.name)} src={addImg} alt="" />
              </div>
            </div>
          </li>
          })
        }
        
      </ul>
      </div>
      <div 
       onClick={(e) => {
        e.stopPropagation();
        setShow(show => !show)
        return false
       }}
      className="total-up-box">
        <img src={carImg} alt="" />
        <span>{totalPrice.toFixed(2)}</span>
      </div>
    </div>
  )
}